import React, { useState, useEffect } from 'react'
import { Card, Table, Select, DatePicker, Row, Col, Statistic, Tag, message, Button } from 'antd'
import { useNavigate } from 'react-router-dom'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'
import { RiseOutlined, FallOutlined, DollarOutlined, ArrowLeftOutlined } from '@ant-design/icons'

const { Option } = Select

const MarketAnalysis: React.FC = () => {
  const navigate = useNavigate()
  const [marketData, setMarketData] = useState<any[]>([])
  const [priceTrend, setPriceTrend] = useState<any[]>([])
  const [selectedProduct, setSelectedProduct] = useState('rice')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchMarketData()
  }, [selectedProduct])

  const fetchMarketData = async () => {
    setLoading(true)
    try {
      // 模拟市场数据
      const mockMarketData = [
        {
          id: '1',
          product: '水稻',
          category: 'grain',
          currentPrice: 2.8,
          unit: '元/公斤',
          change: 0.15,
          changePercent: 5.36,
          market: '本地市场',
          date: '2024-03-16',
          supply: '充足',
          demand: '稳定'
        },
        {
          id: '2',
          product: '小麦',
          category: 'grain',
          currentPrice: 2.5,
          unit: '元/公斤',
          change: -0.08,
          changePercent: -3.10,
          market: '本地市场',
          date: '2024-03-16',
          supply: '充足',
          demand: '一般'
        },
        {
          id: '3',
          product: '玉米',
          category: 'grain',
          currentPrice: 2.2,
          unit: '元/公斤',
          change: 0.05,
          changePercent: 2.27,
          market: '本地市场',
          date: '2024-03-16',
          supply: '充足',
          demand: '旺盛'
        },
        {
          id: '4',
          product: '白菜',
          category: 'vegetable',
          currentPrice: 1.5,
          unit: '元/公斤',
          change: 0.20,
          changePercent: 13.33,
          market: '本地市场',
          date: '2024-03-16',
          supply: '一般',
          demand: '旺盛'
        },
        {
          id: '5',
          product: '猪肉',
          category: 'meat',
          currentPrice: 32.0,
          unit: '元/公斤',
          change: -1.5,
          changePercent: -4.69,
          market: '本地市场',
          date: '2024-03-16',
          supply: '充足',
          demand: '稳定'
        }
      ]

      // 模拟价格趋势数据
      const trendData = {
        rice: [
          { date: '03-10', price: 2.65 },
          { date: '03-11', price: 2.68 },
          { date: '03-12', price: 2.72 },
          { date: '03-13', price: 2.75 },
          { date: '03-14', price: 2.78 },
          { date: '03-15', price: 2.80 },
          { date: '03-16', price: 2.80 }
        ],
        wheat: [
          { date: '03-10', price: 2.58 },
          { date: '03-11', price: 2.55 },
          { date: '03-12', price: 2.53 },
          { date: '03-13', price: 2.52 },
          { date: '03-14', price: 2.50 },
          { date: '03-15', price: 2.48 },
          { date: '03-16', price: 2.50 }
        ]
      }

      setMarketData(mockMarketData)
      setPriceTrend(trendData[selectedProduct as keyof typeof trendData] || [])
    } catch (error) {
      message.error('获取市场数据失败')
    } finally {
      setLoading(false)
    }
  }

  const columns = [
    {
      title: '农产品',
      dataIndex: 'product',
      key: 'product',
      render: (text: string, record: any) => (
        <div>
          <div style={{ fontWeight: 600 }}>{text}</div>
          <Tag color={
            record.category === 'grain' ? 'green' :
            record.category === 'vegetable' ? 'orange' :
            record.category === 'meat' ? 'red' : 'blue'
          }>
            {record.category === 'grain' ? '粮食' :
             record.category === 'vegetable' ? '蔬菜' :
             record.category === 'meat' ? '肉类' : '其他'}
          </Tag>
        </div>
      )
    },
    {
      title: '当前价格',
      dataIndex: 'currentPrice',
      key: 'currentPrice',
      render: (price: number, record: any) => (
        <div style={{ fontWeight: 600, fontSize: '16px' }}>
          {price} {record.unit}
        </div>
      )
    },
    {
      title: '涨跌幅',
      dataIndex: 'change',
      key: 'change',
      render: (change: number, record: any) => {
        const isPositive = change >= 0
        return (
          <div style={{ 
            color: isPositive ? '#f5222d' : '#52c41a',
            fontWeight: 600,
            display: 'flex',
            alignItems: 'center',
            gap: '4px'
          }}>
            {isPositive ? <RiseOutlined /> : <FallOutlined />}
            <span>{isPositive ? '+' : ''}{change} ({isPositive ? '+' : ''}{record.changePercent}%)</span>
          </div>
        )
      }
    },
    {
      title: '市场',
      dataIndex: 'market',
      key: 'market'
    },
    {
      title: '供需状况',
      key: 'supplyDemand',
      render: (record: any) => (
        <div>
          <div>供应: <Tag color={record.supply === '充足' ? 'green' : 'orange'}>{record.supply}</Tag></div>
          <div style={{ marginTop: '4px' }}>需求: <Tag color={record.demand === '旺盛' ? 'red' : 'blue'}>{record.demand}</Tag></div>
        </div>
      )
    },
    {
      title: '更新时间',
      dataIndex: 'date',
      key: 'date'
    }
  ]

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <Button 
              type="text" 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/user-dashboard')}
              style={{ padding: '4px 8px' }}
            >
              返回
            </Button>
            <span>市场行情分析</span>
          </div>
        }
        style={{ marginBottom: '24px' }}
        extra={
          <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
            <Select 
              value={selectedProduct} 
              onChange={setSelectedProduct}
              style={{ width: 120 }}
            >
              <Option value="rice">水稻</Option>
              <Option value="wheat">小麦</Option>
              <Option value="corn">玉米</Option>
            </Select>
            <DatePicker placeholder="选择日期" />
          </div>
        }
      >
        {/* 统计卡片 */}
        <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="平均价格"
                value={2.56}
                precision={2}
                valueStyle={{ color: '#3f8600' }}
                prefix={<DollarOutlined />}
                suffix="元/公斤"
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="最高涨幅"
                value={13.33}
                precision={2}
                valueStyle={{ color: '#cf1322' }}
                prefix={<RiseOutlined />}
                suffix="%"
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="最大跌幅"
                value={-4.69}
                precision={2}
                valueStyle={{ color: '#3f8600' }}
                prefix={<FallOutlined />}
                suffix="%"
              />
            </Card>
          </Col>
        </Row>

        {/* 价格趋势图 */}
        <Card title="价格趋势" style={{ marginBottom: '24px' }}>
          <ResponsiveContainer width="100%" height={300}>
            <LineChart data={priceTrend}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="date" />
              <YAxis />
              <Tooltip />
              <Legend />
              <Line 
                type="monotone" 
                dataKey="price" 
                stroke="#1890ff" 
                strokeWidth={2}
                name="价格(元/公斤)"
              />
            </LineChart>
          </ResponsiveContainer>
        </Card>

        {/* 市场数据表格 */}
        <Card title="农产品价格行情">
          <Table
            loading={loading}
            dataSource={marketData}
            columns={columns}
            rowKey="id"
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true
            }}
          />
        </Card>
      </Card>
    </div>
  )
}

export default MarketAnalysis